package pkg.andru.util;

import java.lang.Thread.UncaughtExceptionHandler;

import android.app.Application;

/**
 * instead of system {@link UncaughtExceptionHandler}, it will save the crash
 * log save to local file.
 * 
 * @author idiottiger
 * @version 1.0
 * 
 */
public class ErrorHandler implements UncaughtExceptionHandler {

    static final String TAG = "CRASH ERROR";

    static UncaughtExceptionHandler mDefaultHandler;

    /**
     * register to handle error, you can in {@link Application} use
     * 
     * @param errorLogFath
     *            the error log path, if is null, will dont save error, just
     *            print to the console
     */
    public static void handleError() {
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new ErrorHandler());
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Log.e(TAG, "--------------- CRASH REPORT START: ---------------------------------------------------\n", ex);
        Log.e(TAG, "--------------- CRASH REPORT END  : ---------------------------------------------------\n");
        final Throwable finalEx = ex;
        final Thread finalThread = thread;
        Log.ensureBackupAllLogs();
        mDefaultHandler.uncaughtException(finalThread, finalEx);
    }
}
